package com.heima.user.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 手机号密码登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto dto) {
        //游客登录
        if (ObjectUtil.hasEmpty(dto.getPhone(), dto.getPassword())) {
            return ResponseResult.okResult(MapUtil.<String, Object>builder()
                    .put("token", AppJwtUtil.getToken(0L))
                    .build());
        }

        LambdaQueryWrapper<ApUser> queryWrapper = Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getPhone, dto.getPhone());
        ApUser apUser = this.baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(apUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "用户不存在");
        }


        String password = DigestUtil.md5Hex(dto.getPassword() + apUser.getSalt());
        if (ObjectUtil.notEqual(apUser.getPassword(), password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        apUser.setPassword(null);
        apUser.setSalt(null);

        return ResponseResult.okResult(MapUtil.<String, Object>builder()
                .put("token", AppJwtUtil.getToken(Convert.toLong(apUser.getId())))
                .put("user", apUser).build());
    }
}
